import { ElMessage } from "element-plus";

/**
 *  获取详细的数据类型
 * @param x
 */
export const getDataType = (x: any): string => {
    const originType = Object.prototype.toString.call(x);
    const spaceIndex = originType.indexOf(' ');
    const type = originType.slice(spaceIndex + 1, -1);
    return type.toLowerCase();
}

export const typeIsString = (x: any) => {
    return getDataType(x) === 'string';
};

export const typeIsNumber = (x: any) => {
    return getDataType(x) === 'number';
};

export const typeIsArray = (x: any) => {
    return getDataType(x) === 'array';
};

export const typeIsObject = (x: any) => {
    return getDataType(x) === 'object';
};

export const typeIsFun = (x: any) => {
    return getDataType(x).includes('function');
};

/**
 * 防抖
 * @param fn
 * @param delay
 */
export const debounce = (fn: Function, delay: number = 500) => {
    // 定义一个定时器，保存上一次的定时器
    let timer: any = null
    return function (...args: any) {
        // 取消上一次的定时器
        if (timer) clearTimeout(timer)
        // 延迟执行
        timer = setTimeout(() => {
            // 外部传入的真正要执行的函数
            fn.apply(this, args)
        }, delay);
    }
}


/**
 * 下载图片
 * @param href
 */
export const downloadLink = (href: string) => {
    let link = document.createElement('a');
    link.href = href;
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
}

/**
 * 复制文本
 * @param text
 */
export const copyText = (text: string) => {
    copyToClipboard(text).then(() => {
        ElMessage.success('复制成功');
    }).catch(() => {
        ElMessage.error('复制失败');
    })
}

export const copyToClipboard = (text: string) => {
    try {
        return navigator.clipboard.writeText(text);
    } catch {
        const t = document.createElement('textarea');
        t.nodeValue = text;
        t.value = text;
        t.style.position = 'fixed';
        t.style.opacity = '0';
        t.style.left = '-99px';
        document.body.appendChild(t);
        t.select();
        return new Promise<void>((res, rej) => {
            // 执行复制命令并移除文本框
            document.execCommand('copy') ? res() : rej();
            t.remove();
        });
    }
}

